/**
 * @author 韩
 */

import * as echarts from "echarts"
import { mapData } from "./mapData"

//默认模式 标准模式还是暗黑模式
const echartsMode = "dark" //可选值：暗黑模式：dark   普通模式：undefined
let colorList = ["rgb(26,168,192)", "rgb(71,119,245)", "rgb(80,69,246)", "rgb(173,70,243)", "rgb(248,69,241)",] //拆线 柱子图（按顺序自动取颜色）

// 默认横轴日期数据
const defaultDayList = ['2022/04', '2022/05', '2022/06', '2022/07', '2022/08', '2022/09']

// 默认地图数据
var airData = [
  { name: '北京市', value: 0 },
  { name: '天津市', value: 0 },
  { name: '河北省', value: 0 },
  { name: '山西省', value: 0 },
  { name: '内蒙古自治区', value: 0 },
  { name: '辽宁省', value: 0 },
  { name: '吉林省', value: 0 },
  { name: '黑龙江省', value: 0 },
  { name: '上海市', value: 0 },
  { name: '江苏省', value: 0 },
  { name: '浙江省', value: 0 },
  { name: '安徽省', value: 0 },
  { name: '福建省', value: 0 },
  { name: '江西省', value: 0 },
  { name: '山东省', value: 0 },
  { name: '河南省', value: 0 },
  { name: '湖北省', value: 0 },
  { name: '湖南省', value: 0 },
  { name: '广东省', value: 13, children: [{ name: "广州", value: 1 }, { name: "深圳", value: 12 }] },
  { name: '广西壮族自治区', value: 0 },
  { name: '海南省', value: 0 },
  { name: '重庆市', value: 0 },
  { name: '四川省', value: 0 },
  { name: '贵州省', value: 0 },
  { name: '云南省', value: 0 },
  { name: '西藏自治区', value: 0 },
  { name: '陕西省', value: 0 },
  { name: '甘肃省', value: 0 },
  { name: '青海省', value: 0 },
  { name: '宁夏回族自治区', value: 0 },
  { name: '新疆维吾尔自治区', value: 0 },
  { name: '台湾省', value: 0 },
  { name: '香港特别行政区', value: 0 },
  { name: '澳门特别行政区', value: 0 },
  { name: '南海诸岛', value: 0 }
]


// 扇形图计算比例 %
const formaitList = (array) => {
  // console.log('接收到的数组：', array)
  //
  let list = [];
  let total = 0;
  for (var j = 0; j < array.length; j++) {
    var value = array[j].value;
    var n = value[value.length - 1]
    total = total + n
  }

  for (var i = 0; i < array.length; i++) {
    var obj = {}
    obj.name = array[i].name;
    var value = array[i].value;
    var n = value[value.length - 1]
    obj.value = value;
    obj.scale = (n / total * 100).toFixed(2);
    list.push(obj)
  }
  return list
}

// 提取xAxis数组
const getXAxis = (array) => {
  // data: ['20岁以下', '21~30岁', '31~40岁', '41~50岁', '50~60岁', '61岁以上']
  let list = [];
  for (var i = 0; i < array.length; i++) {
    var str = array[i].name
    list.push(str)
  }
  // console.log(list)

  return list
}

// 提取xAxis数组
const getYAxis = (array) => {
  // data: [120, 200, 150, 80, 70, 110],
  // 拿最后一个，最后一个是当前月份的或者当前年代的数据
  let list = [];
  for (var i = 0; i < array.length; i++) {
    var value = array[i].value;
    var n = value[value.length - 1];
    list.push(n)
  }
  // console.log(list)
  return list
}

// 拆线图 提取series数据
const getSeries = (array, area) => {

  let list = [];
  for (var i = 0; i < array.length; i++) {
    var obj = {
      // color:colorList[i],
      areaStyle: area ? {} : null,
      name: array[i].name,
      type: 'line',
      stack: 'Total',
      data: array[i].value,
    }
    list.push(obj)
  }
  return list;
}

// 堆叠图提取数据
const getSeriesAdBar = (array, adType) => {

  var list = [];
  for (var i = 0; i < array.length; i++) {
    var name = array[i].name
    var obj = {
      // barMaxWidth:25,
      name: array[i].name,
      type: 'bar',
      stack: adType ? "Ad" : undefined,
      // color:colorList[i],
      emphasis: {
        focus: 'series'
      },
      data: array[i].value,
      // legend: {
      //   show: (name==="真实率"||name==="完整率")?false:null,//隐藏副标题
      // },
      // legend:(name==="真实率"||name==="完整率")?false:null,
      // barWidth:(name==="真实率"||name==="完整率")?0.00001:25,
      // barMaxWidth:(name==="真实率"||name==="完整率")?0.00001:20,
      barMaxWidth: 20,

      // itemStyle:(name==="真实率"||name==="完整率")?{color:"rgba(0,0,0,0)"}:null
    }
    list.push(obj)
  }
  return list;


}

// 折线图 提取name
const getLegend = (array) => {
  var list = []
  for (var i = 0; i < array.length; i++) {
    var str = array[i].name
    list.push(str)
  }
  return list
}




// 扇形图
const pieChart = ({ unit = "", toFixed = false, echartOptions = {
  legend: {},
}, showLegend = true, margin = ["20px", "20px", "20px", "20px"], state, title, event, type }) => {


  // console.log("扇形图接收到的数据：state\n", state)
  var myChart = echarts.init(event, echartsMode);
  myChart.clear()

  var option = {
    backgroundColor: 'rgba(0,0,0,0)', //设置无背景色
    // color:colorList,
    title: {
      text: title,
      subtext: '占比',
      left: 'center',
      show: false  //隐藏大标题
    },
    tooltip: {
      trigger: 'item',
      // formatter: `{b} : {c}万元 ({d}%)`
      formatter: function (params) {
        // console.log("params", params)
        return `${params.name}:${toFixed ? Number(params.value).toFixed(2) : Number(params.value)}${unit} （${params.percent}%）`
      }
    },
    legend: {
      ...echartOptions.legend,
      show: showLegend //隐藏标签标题
    },
    grid: {
      top: margin[0] || '20px',
      left: margin[1] || '20px',
      right: margin[2] || '20px',
      bottom: margin[3] || '20px',

      containLabel: true
    },
    series: [
      {
        //   name: '客户性别分布',
        type: 'pie',
        // radius:'50%',
        radius: (() => {
          if (type === "2") {
            return ['30%', '50%']
          } else {
            return "50%"
          }
        })(),
        center: ['50%', '50%'],

        data: formaitList(state.data),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    label: {
      alignTo: 'edge',
      formatter: `{name|{b}}\n{time|{c}}`,
      minMargin: 5,
      edgeDistance: 10,
      lineHeight: 15,
      rich: {
        time: {
          fontSize: 10,
          color: '#999'
        }
      }
    },
  };
  option && myChart.setOption(option);
  myChart.resize()

}

// 柱形图
const colChart = ({ unit = "", toFixed = false, axisRotate, showLegend = false, margin = ["20px", "20px", "20px", "20px"], state, title, event, useXis }) => {
  var myChart = echarts.init(event, echartsMode);
  myChart.clear()
  var option;

  option = {
    backgroundColor: 'rgba(0,0,0,0)', //设置无背景色
    tooltip: {
      show: true,
    },
    legend: {
      show: showLegend//隐藏副标题
    },
    xAxis: {
      type: 'category',
      data: getXAxis(state.data),
      // data: ['20岁以下', '21~30岁', '31~40岁', '41~50岁', '50~60岁', '61岁以上']
      splitLine: {
        show: false
      },
      axisLabel: {
        interval: 0,
        rotate: 30,

      }
    },

    yAxis: {
      type: 'value',
      splitLine: {
        show: false
      }
    },
    grid: {
      top: margin[0] || '20px',
      left: margin[1] || '20px',
      right: margin[2] || '20px',
      bottom: margin[3] || '20px',
      containLabel: true
    },
    series: [
      {
        // data: [120, 200, 150, 80, 70, 110],
        data: getYAxis(state.data),

        type: 'bar',
        tooltip: {
          formatter: function (params) {
            // console.log("柱子提示内容", params)
            return `${params.name}：${params.value}${unit}`
          }
        },
        barMaxWidth: 25,
        itemStyle: {
          // color:colorList[0],
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: '#83bff6' },
          //   { offset: 0.5, color: '#13c2e9' },
          //   { offset: 1, color: '#188df0' }
          // ])
        },
      }
    ]
  };
  option && myChart.setOption(option);
  myChart.resize()
}

// 拆线趋势图

const lineChart = ({ toFixed = false, area, showLegend = false, margin = ["20px", "20px", "20px", "20px"], state, title, event, useXis, dayList = defaultDayList }) => {

  var myChart = echarts.init(event, echartsMode);
  myChart.clear()
  var option;
  option = {
    backgroundColor: 'rgba(0,0,0,0)', //设置无背景色
    title: {
      text: 'Stacked Line',
      show: false,
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: getLegend(state.data),
      show: showLegend//显示小标题
    },
    grid: {

      top: margin[0] || '20px',
      left: margin[1] || '20px',
      right: margin[2] || '20px',
      bottom: margin[3] || '20px',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {
          show: false
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      splitLine: {
        show: false
      },
      data: (function () {
        if (useXis === true) {
          return state.dayList
        } else {
          return dayList
        }
      })()
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: false
      }
    },
    series: getSeries(state.data, area),
  };

  option && myChart.setOption(option);
  myChart.resize()
}

// 堆叠图  adType="Ad" 表示竖条堆叠，
const adBarChart = ({ unit = "", toFixed = false, addTooltip, adType = false, showLegend = false, margin = ["20px", "20px", "20px", "20px"], state, title, event, useXis, dayList = defaultDayList }) => {

  var myChart = echarts.init(event, echartsMode);
  myChart.clear()
  var option = {
    backgroundColor: 'rgba(0,0,0,0)', //设置无背景色
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        // console.log("tooltop:\n", params)
        var tooltop = params[0].axisValueLabel + '<br/>';
        // 先拿出tooltip要增加的自定义数据
        //   {
        //     "name": "真实率",
        //     "value": getRandomMath(1000, 98884, 6, 2),
        // },
        // {
        //     "name": "完整率",
        //     "value": getRandomMath(1000, 98884, 6, 2),
        // },
        let obj1 = addTooltip ? state.tooltipData[0] : null;
        let obj2 = addTooltip ? state.tooltipData[1] : null;

        var span1 = "";
        var span2 = "";
        params.forEach(item => {
          // console.log('tooltopitem\n', item, "axisIndex是：" + item.dataIndex)
          var itemSpan = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color};"></span>${item.seriesName}:${toFixed ? Number(item.value).toFixed(2) : Number(item.value)}${unit ? unit : ""}<br/>`
          tooltop = tooltop + itemSpan;
          if (addTooltip) {
            span1 = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;"></span>${obj1.name}:${toFixed ? Number(obj1.value[item.dataIndex]) : Number(obj1.value[item.dataIndex])}${unit ? unit : ""}<br/>`
            span2 = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;"></span>${obj2.name}:${toFixed ? Number(obj2.value[item.dataIndex]).toFixed(2) : Number(obj2.value[item.dataIndex])}${unit ? unit : ""}<br/>`

          }

        })
        // 判断tooltipData存在不存在
        if (addTooltip) {
          tooltop = tooltop + span1 + span2
        }

        return tooltop
      },
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      show: showLegend//隐藏副标题
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: useXis ? state.dayList : defaultDayList,
        splitLine: {
          show: false
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: false
        }
      }
    ],
    series: getSeriesAdBar(state.data, adType),
  };
  option && myChart.setOption(option);
  myChart.resize()
}

// 漏斗图
const funnelChart = ({ toFixed = false, event, showLegend, margin = ["20px", "20px", "20px", "20px"], state }) => {
  var myChart = echarts.init(event, echartsMode);
  myChart.clear()
  var option = {
    backgroundColor: 'rgba(0,0,0,0)', //设置无背景色
    title: {
      text: 'Funnel',
      show: false
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}%'
    },
    toolbox: {
      show: false, //隐藏下载按钮等自带的切换类型按钮
      feature: {
        dataView: { readOnly: false },
        restore: {},
        saveAsImage: {}
      }
    },
    legend: {
      // data: ['Show', 'Click', 'Visit', 'Inquiry', 'Order'],
      // data:(function(){
      //   var list= ['Show', 'Click', 'Visit']
      //   return list
      // })(),
      show: showLegend
    },
    series: [
      {
        name: 'Funnel',
        type: 'funnel',
        left: '10%',
        top: 60,
        bottom: 60,
        width: '80%',
        min: 0,
        max: 100,
        minSize: '0%',
        maxSize: '100%',
        sort: 'descending',
        gap: 2,
        label: {
          show: true,
          position: 'inside'
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        emphasis: {
          label: {
            fontSize: 20
          }
        },
        data: state.data
      }
    ]
  };
  option && myChart.setOption(option);
  myChart.resize()
}


// 中国地图
const chinaMap = async ({ event, state }, fun) => {
  var mCharts = echarts.init(event)
  mCharts.clear()
  // const res = await http.get(API_MAP)
  const res = mapData;
  if (res) {
    echarts.registerMap('chinaMap', res)
    var option = {
      tooltip: {
        formatter: function (params) {
          // console.log(params.data);
          return `${params.data.name}：${params.data.value}`
        }
      },

      geo: {
        type: 'map',
        map: 'chinaMap',    //这里的值要和上面registerMap的第一个参数一致
        roam: false,  //默认是否开启鼠标缩放地图
        label: {
          show: false,       //展示标签
        },
        zoom: 1.2,
        itemStyle: {
          normal: {
            borderWidth: 1, //边际线大小
            borderColor: '#00ffff', //边界线颜色
            areaColor: '#09295b' //默认区域颜色
          },
          emphasis: {
            show: true,
            areaColor: '#3066ba', //鼠标滑过区域颜色
            label: {
              show: true,
              textStyle: {
                color: 'white'//鼠标经过字体颜色
              }
            }
          }
        },
      },
      series: [
        {
          data: state,
          geoIndex: 0,      //将空气质量的数据和第0个geo配置关联在一起
          type: 'map',

        }
      ],
      visualMap: {
        min: 0,
        max: 300,
        inRange: {
          color: ['rgb(1,88,182)', 'rgb(23,188,235)']   //控制颜色渐变的范围
        },
        calculable: true,      //出现滑块
        show: true
      }
    }
    mCharts.setOption(option)
  } else {
    console.log("地图数据请求出错！")
  }

  mCharts.on('click', function (res) { //点击了地图
    const { comCode } = res.data;
    console.log("当前点击的省：", comCode);
    // const province = state.find(item => item.name === res.name)
    fun({ comCode: comCode })

  });

}

// 环形图
const Doughnut = (event, object) => {

  const myChart = echarts.init(event, "dark");
  myChart.clear()
  myChart.setOption({
    backgroundColor: '', //设置无背景色
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center',
      show: false
    },
    series: [
      {
        name: object.name,
        type: 'pie',
        radius: ['70%', '90%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 1,
          borderColor: 'rgba(0,0,0,0)',
          borderWidth: 1
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
            fontSize: '40',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: object.data
      }
    ]
  });
};

// 仪表图
const Speed = ({ event, data, color }) => {

  const myChart = echarts.init(event, "dark");
  myChart.setOption({
    backgroundColor: '', //设置无背景色
    series: [
      {
        color: color ? color : undefined,//主体环颜色
        radius: '90%',
        type: 'gauge',
        progress: {
          show: true,
          width: 8
        },
        axisLine: {
          lineStyle: {
            width: 8,
            // color: [ //空白环颜色
            //     [1, "orange"],
            // ]
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false,
          length: 0,
          lineStyle: {
            width: 4,
            color: '#999'
          }
        },
        axisLabel: {
          distance: 2,
          color: '#999',
          fontSize: 12
        },
        anchor: {
          show: true,
          showAbove: true,
          size: 12,
          itemStyle: {
            borderWidth: 2
          }
        },
        title: {
          show: false
        },
        detail: {
          valueAnimation: true,
          offsetCenter: [0, '70%'],
          fontSize: 12,
          fontWeight: 600,
          formatter: '{value} %',
        },
        data: [
          {
            value: data,
          }
        ]
      }
    ]
  });
};


export {
  pieChart, colChart, lineChart, chinaMap, adBarChart,
  Doughnut, Speed, funnelChart

}